package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojo.WmMaterial;
import com.heima.model.wemedia.pojo.WmNewsMaterial;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.MaterialService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class MaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements MaterialService {

    @Autowired
    private FileStorageService fileStorageService;
    @Value("${file.oss.prefix}")
    private String prefix;
    @Value("${file.oss.web-site}")
    private String website;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.参数校验（文件对象，判断是否登陆，文件后缀是否支持）
        if (multipartFile == null||multipartFile.getSize() <= 0) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请上传正确的文件");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //获取原始文件名称[jpg,jpeg,png,gif]
        String originalFilename = multipartFile.getOriginalFilename();
        if (!checkFileSuffix(originalFilename)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文件类型不支持，目前支持：[jpg,jpeg,png,gif]");
        }
        //2.上传到OSS(生成新的文件名称，上传到oss)
        String filePath = null;
        try {
            String newFileName = UUID.randomUUID().toString().replaceAll("-","");
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            filePath = fileStorageService.store(prefix, newFileName + suffix, multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"上传文件失败");
        }
        //3.保存到数据库
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(user.getId());
        wmMaterial.setUrl(filePath);
        wmMaterial.setType((short)0);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);
        //4.封装返回,需要将url的路径不全，用于前端回显图片
        wmMaterial.setUrl(website+wmMaterial.getUrl());

        return ResponseResult.okResult(wmMaterial);
    }

    private boolean checkFileSuffix(String originalFilename) {
        if (StringUtils.isNotBlank(originalFilename)){
            List<String> list = Arrays.asList(".jpg", ".jpeg", "png", "gif");
            for (String s : list) {
                if (originalFilename.endsWith(s)){
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        // 1 参数校验
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2 执行业务查询
        //分页查询
        Page<WmMaterial> pageReq = new Page<>(dto.getPage(),dto.getSize());
        //查询条件(收藏条件，用户id，发布时间降序)
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.lambdaQuery();
        if (dto.getIsCollection().equals(Short.parseShort("1"))){
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //查询自己上传的素材
        wrapper.eq(WmMaterial::getUserId,user.getId());
        //按照发布时间降序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        // 3 封装结果
        IPage<WmMaterial> page = page(pageReq, wrapper);
        List<WmMaterial> records = page.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(website + record.getUrl());
        }
        return new PageResponseResult(dto.getPage(),dto.getSize(),page.getTotal(),records);
    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    @Override
    public ResponseResult delPicture(Integer id) {
        // 1 参数校验
        if (id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2 业务处理
        // 判断当前id是否被引用，如果被使用则禁止删除
        WmMaterial byId = getById(id);
        if (byId == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId,id);
        Integer integer = wmNewsMaterialMapper.selectCount(wrapper);
        if (integer > 0){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        // 删除素材库
        removeById(id);
        // 删除图片OSS
        fileStorageService.delete(byId.getUrl());
        // 3 封装结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.检查参数
        if (id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.更新状态
        WmMaterial material = getById(id);
        if (material == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"素材信息不存在");
        }
        //获取当前用户信息
        Integer uid = WmThreadLocalUtils.getUser().getId();
        if (!material.getUserId().equals(uid)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"只允许收藏自己上传的素材");
        }
        material.setIsCollection(type);
        updateById(material);
        return ResponseResult.okResult();
    }


}
